package com.vueblog.webapi.shiro;

import com.vueblog.webapi.entity.UserEntity;
import com.vueblog.webapi.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author lsj
 * @create 2021-05-27 23:04
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 执行认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //从数据库查到用户
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;//类型转换
        UserEntity user = userService.getUserByName(token.getUsername());
        if(user==null){
            return null;// Controller中login会自动抛出异常 UnknownAccountException
        }
        //shiro帮我们做密码认证 如下的user即为放入的principal，之后想要获取user可以 subject.getPrincipal()
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}